package com.fang.service;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import redis.clients.jedis.Jedis;

import com.fang.dao.CartDao;
import com.fang.dao.GoodsDao;
import com.fang.dao.OrdersDao;
import com.fang.entity.Cart;
import com.fang.entity.Goods;
import com.fang.entity.Orders;
import com.fang.entity.OrdersItem;
import com.fang.entity.PCD;
import com.fang.utils.JDBCUtils;
import com.google.gson.Gson;

public class OrdersService {
	OrdersDao dao = new OrdersDao();
	CartDao cdao = new CartDao();
	public String queryPCD(String pid) {
		List<PCD> list = dao.queryPCDbypid(pid);
		Gson gson = new Gson();
		String json = gson.toJson(list);
		return (json);
	}

	public void submit(Orders orders, List<OrdersItem> olist) {
		// 获取连接对象
		Connection con=null;
		try {
			con = JDBCUtils.getConnection();
			// 设置事务手动提交
			con.setAutoCommit(false);
			// 1. 添加订单
			dao.addOrders(orders);
			// 2. 添加订单明细
			dao.addOrdersItem(olist);
			// 3. 清空购物车:调用购物车的DAO
			cdao.clear(orders.getUid());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			// 回滚事务
			if(con!=null)
				try {
					con.rollback();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		} finally{
			//提交事物
			if(con!=null){
				try {
					con.commit();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public List<Orders> query(int uid) {
		OrdersDao dao = new OrdersDao();
		return dao.querybyuid(uid);
	}

	public void cansel(int uid, String id) {
		OrdersDao dao = new OrdersDao();
		dao.cansel(uid,id);
		
	}

	public Orders queryorders(String id, int uid) {
		OrdersDao dao = new OrdersDao();
		Orders orders = dao.query(id,uid);
		return orders;
	}

	public List<OrdersItem> queryitem(String id) {
		OrdersDao dao = new OrdersDao();
		GoodsDao gdao = new GoodsDao();
		List<OrdersItem> list = dao.queryitem(id);
		
		for (OrdersItem item : list) {
			Goods goods  = new Goods();
			goods.setId(item.getGid());
			List<Goods> list2 = gdao.querygoods(goods);
			item.setGoods(list2.get(0));
		}
		return list;
	}

	public void newadd(int uid, String id) {
		OrdersDao dao = new OrdersDao();
		dao.newadd(uid,id);
	}

	public void paysuccess(int uid, String id) {
		OrdersDao dao = new OrdersDao();
		dao.paysucess(uid,id);
	}


	
}
